<template>
  <div>
    <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
      <a-form-item label="头像" name="userAvatar">
        <div class="avatar-upload">
          <a-upload
            :file-list="[]"
            :before-upload="beforeUpload"
            :show-upload-list="false"
            accept="image/*"
          >
            <div class="avatar-wrapper">
              <a-avatar
                :size="80"
                :src="form.userAvatar || defaultAvatar"
                style="cursor: pointer"
              />
              <div class="avatar-overlay">
                <CameraOutlined />
              </div>
            </div>
          </a-upload>
        </div>
      </a-form-item>

      <a-form-item label="用户名" name="userName">
        <a-input v-model:value="form.userName" placeholder="请输入用户名" :maxlength="50" />
      </a-form-item>

      <a-form-item label="个人简介" name="userProfile">
        <a-textarea
          v-model:value="form.userProfile"
          placeholder="请输入个人简介"
          :rows="4"
          :maxlength="500"
          show-count
        />
      </a-form-item>

      <a-form-item label="用户标签" name="tags">
        <a-select
          v-model:value="form.tags"
          mode="tags"
          placeholder="请选择或输入标签"
          :max-tag-count="5"
          style="width: 100%"
        >
          <a-select-option v-for="tag in systemTags" :key="tag" :value="tag">
            {{ tag }}
          </a-select-option>
        </a-select>
        <div style="color: #999; font-size: 12px; margin-top: 4px">
          可选择系统标签或自定义输入，最多5个标签
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { CameraOutlined } from '@ant-design/icons-vue'
import { message, type FormInstance, type UploadProps } from 'ant-design-vue'
import { updateUserSelf } from '@/api/userController'
import { listTag } from '@/api/tagController'

interface Props {
  userInfo: API.LoginUserVO
}

interface Emits {
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const defaultAvatar = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png'

// 系统标签选项（动态获取）
const systemTags = ref<string[]>([])

// 获取系统标签数据
const fetchSystemTags = async () => {
  try {
    const res = await listTag({})
    if (res.data.code === 200 && res.data.data) {
      systemTags.value = res.data.data.map((tag: API.TagVO) => tag.tagName || '').filter(Boolean)
      console.log('获取系统标签成功:', systemTags.value)
    } else {
      console.error('获取系统标签失败:', res.data.message)
      // 如果获取失败，使用备用的基础标签
      systemTags.value = ['旅行', '摄影', '美食', '文化', '户外']
    }
  } catch (error) {
    console.error('获取系统标签异常:', error)
    // 如果获取失败，使用备用的基础标签
    systemTags.value = ['旅行', '摄影', '美食', '文化', '户外']
  }
}

// 表单数据
const form = reactive({
  id: 0,
  userName: '',
  userAvatar: '',
  userProfile: '',
  tags: [] as string[],
  avatarFile: null as File | null, // 存储头像文件
})

// 表单验证规则
const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 50, message: '用户名长度在 1 到 50 个字符', trigger: 'blur' },
  ],
}

// 监听props变化，初始化表单
watch(
  () => props.userInfo,
  (newUserInfo) => {
    if (newUserInfo && newUserInfo.id) {
      console.log('初始化用户信息表单:', newUserInfo)
      form.id = newUserInfo.id
      form.userName = newUserInfo.userName || ''
      form.userAvatar = newUserInfo.userAvatar || ''
      form.userProfile = newUserInfo.userProfile || ''

      // 处理标签数据
      let userTags: string[] = []
      if (newUserInfo.tags) {
        try {
          // 如果是字符串，尝试解析为JSON数组
          if (typeof newUserInfo.tags === 'string') {
            userTags = JSON.parse(newUserInfo.tags)
          } else if (Array.isArray(newUserInfo.tags)) {
            userTags = newUserInfo.tags
          }
        } catch (error) {
          console.error('解析用户标签失败:', error)
          userTags = []
        }
      }
      form.tags = userTags
      form.avatarFile = null

      console.log('表单初始化完成:', form)
    }
  },
  { immediate: true },
)

// 头像上传前处理
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  console.log('准备设置头像:', file)

  const isImage = file.type?.startsWith('image/')
  if (!isImage) {
    message.error('只能上传图片文件!')
    return false
  }

  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    message.error('图片大小不能超过 5MB!')
    return false
  }

  // 存储文件对象，用于后续提交
  form.avatarFile = file

  // 创建预览URL
  const previewUrl = URL.createObjectURL(file)
  form.userAvatar = previewUrl

  console.log('头像文件设置成功:', file.name)
  message.success('头像选择成功，保存时会自动上传')

  return false // 阻止自动上传
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value?.validate()

    console.log('提交用户信息更新:', form)

    // 创建FormData
    const formData = new FormData()
    formData.append('id', form.id.toString())
    formData.append('userName', form.userName)
    formData.append('userProfile', form.userProfile || '')

    // 添加标签数据
    form.tags.forEach((tag) => {
      formData.append('tags', tag)
    })

    // 添加头像文件（如果有新上传的）
    if (form.avatarFile) {
      formData.append('userAvatar', form.avatarFile)
      console.log('包含新头像文件:', form.avatarFile.name)
    }

    console.log('调用用户更新API，FormData内容:')
    for (const [key, value] of formData.entries()) {
      console.log(key, value)
    }

    const res = await updateUserSelf(formData)
    console.log('用户更新响应:', res)

    if (res.data.code === 200) {
      message.success('个人信息更新成功')
      console.log('用户信息更新成功，触发成功事件')
      emit('success')
    } else {
      console.error('用户信息更新失败:', res.data.message)
      message.error('更新失败: ' + res.data.message)
    }
  } catch (error) {
    console.error('用户信息更新异常:', error)
    if (error && typeof error === 'object' && 'errorFields' in error) {
      message.error('请检查表单输入')
    } else {
      message.error('更新失败，请稍后重试')
    }
  }
}

// 重置表单
const handleReset = () => {
  if (props.userInfo && props.userInfo.id) {
    form.id = props.userInfo.id
    form.userName = props.userInfo.userName || ''
    form.userAvatar = props.userInfo.userAvatar || ''
    form.userProfile = props.userInfo.userProfile || ''

    // 重置标签
    let userTags: string[] = []
    if (props.userInfo.tags) {
      try {
        if (typeof props.userInfo.tags === 'string') {
          userTags = JSON.parse(props.userInfo.tags)
        } else if (Array.isArray(props.userInfo.tags)) {
          userTags = props.userInfo.tags
        }
      } catch (error) {
        console.error('重置时解析用户标签失败:', error)
        userTags = []
      }
    }
    form.tags = userTags
    form.avatarFile = null

    console.log('表单已重置为初始值')
  }
}

// 暴露方法给父组件
defineExpose({
  handleSubmit,
  handleReset,
})

// 组件挂载时获取系统标签
onMounted(() => {
  fetchSystemTags()
})
</script>

<style scoped>
.avatar-upload {
  display: flex;
  justify-content: center;
  margin-bottom: 16px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
}

.avatar-wrapper:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.4);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
  color: white;
  font-size: 20px;
}

/* 移动端优化 */
@media (max-width: 768px) {
  .avatar-upload {
    margin-bottom: 12px;
  }

  .avatar-overlay {
    font-size: 16px;
  }
}
</style>
